import { defineStore } from 'pinia'
import { type Device, type TableDataRow, TableHeader, type TableRow } from '@/types/device'
import { addDevice as addDeviceApi, getDeviceList, } from '@/api/deviceApi'
import {
  getSlaveTable as getSlaveTableApi,
  readRegister as readRegisterApi,
  setSlaveAddress as setSlaveAddressApi
} from '@/api/slaveApi';
import { ref } from 'vue';

export const useDeviceStore = defineStore('device', () => {
  const selectedRows = ref<TableDataRow[]>([]);

  // 更新selectedRows里面某一地址的值
  const updateSelectedRows = (address: number, data: TableDataRow) => {
    for (let i = 0; i < selectedRows.value.length; i++) {
      if (selectedRows.value[i][TableHeader.Address] === address) {
        selectedRows.value.splice(i, 1, {
          ...selectedRows.value[i],
          [TableHeader.RegisterValue]: data.value,
          [TableHeader.Status]: data.status,
          [TableHeader.LastUpateTime]: data.time
        })
      }
    }
  }

  const addDevice = async (device: Device): Promise<boolean> => {
    return await addDeviceApi(device);
  }

  const getDevice = async (deviceName: string): Promise<Device> => {
    const deviceList: Array<Device> = await getDeviceList();

    for (const device of deviceList) {
      if (device.name === deviceName) {
        return device;
      }
    }
    return {
      id: 0,
      name: "Unknown Device",
      ip: "0.0.0.0",
      port: 0,
      protocol: "Unknown",
      isConnected: false,
    };
  }

  const setSlaveAddress = async (deviceName: string, slaveId: number, registerType: number, startAddress: number,
    endAddress: number): Promise<boolean> => {
    return await setSlaveAddressApi(deviceName, slaveId, registerType, startAddress, endAddress);
  }

  const getSlaveTable = async (deviceName: string, slaveId: number, registerType: number):
    Promise<any> => {
    const data: number[] = await getSlaveTableApi(deviceName, slaveId, registerType);
    return data.map(item => ({
      address: item,
      value: undefined,
      status: undefined,
      time: ""
    }));
  }

  const readRegister = async (deviceName: string, slaveId: number, registerType: number, startAddress: number,
    endAddress: number): Promise<TableRow[]> => {
    const data: TableRow[] = await readRegisterApi(deviceName, slaveId, registerType, startAddress, endAddress);
    if (data && data.length > 0) {
      return data.map(item => ({
        address: item.address,
        status: item.status,
        value: item.status === true ? item.value : undefined,
        time: item.time
      }))
    } else {
      return []
    }
  }

  return {
    selectedRows,
    updateSelectedRows,
    addDevice,
    getDevice,
    setSlaveAddress,
    getSlaveTable,
    readRegister
  }
})
